package pl.model.domain.validator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import pl.common.Util;
import pl.controller.add.AddBookBackingObject;
import pl.model.dao.AuthorDao;
import pl.model.dao.BookDao;
import pl.model.dao.CommentDao;
import pl.model.dao.PublisherDao;
import pl.model.dao.UserDao;
import pl.model.domain.Book;

public class BookValidator implements Validator {

	Log log = LogFactory.getLog(this.getClass());
	
	protected BookDao bookDao;
	protected AuthorDao authorDao;
	protected CommentDao commentDao;
	protected PublisherDao publisherDao;
	protected UserDao userDao;
	
	@Override
	public boolean supports(Class clazz) {
		return clazz.equals(AddBookBackingObject.class);
	}

	@Override
	public void validate(Object target, Errors errors) {
		AddBookBackingObject abbo = (AddBookBackingObject) target;
		Book book = abbo.book;

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "field.required", "Podaj tytul");
		
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description", "field.required", "Podaj opis");
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "tags", "field.required", "Podaj tagi");
		
		ValidationUtils.rejectIfEmpty(errors, "author", "field.required", "Brakuje autora");
		
		if (book.getRank() == null){
			log.debug("rank validation err: " + book.getRank() + ".");
			errors.rejectValue(null, "err.rank", "Podaj rank");
		} else {
			log.debug("rank validation ok: " + book.getRank() + ".");
		}
		
		if (bookDao.findByTitle(book.getTitle()).size()>0){
			log.debug("juz istnieje");
			errors.reject("err.title", "juz istnieje ksiazka z takim tytulem");
			errors.rejectValue("title", "err.title", "Juz istnieje ksiazka o tym tytule");
		}
		
		if (!abbo.getCaptchaReal().equals(abbo.getSessionData().getCaptcha())){
			log.debug("niezgodne captcha " + abbo.getCaptchaReal() + " != " + abbo.getSessionData().getCaptcha());
			errors.reject("err", "Wygladasz na boota3");
		//	errors.rejectValue("captcha", "err.captcha2", "Lets try again");
			
		}
		if (errors.getErrorCount()>0){
			
			abbo.getSessionData().setCaptcha(Util.randomCaptcha());
			log.debug("resetting captcha to: " + abbo.getSessionData().getCaptcha());
		}
	}

	public void setBookDao(BookDao bookDao) {
		this.bookDao = bookDao;
	}

	public void setAuthorDao(AuthorDao authorDao) {
		this.authorDao = authorDao;
	}

	public void setCommentDao(CommentDao commentDao) {
		this.commentDao = commentDao;
	}

	public void setPublisherDao(PublisherDao publisherDao) {
		this.publisherDao = publisherDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}
